import {ElMessage, ElMessageBox} from "element-plus";
import service from '@/utils/request.ts'

enum HandleEnum {
    SUCCESS = 'success',
    FAILED = 'failed'
}

function deleteRow(url:string,data:{},callback = (state:HandleEnum,data:any) => {}){
    ElMessageBox.confirm(
        '是否删除数据【请确认是否影响关联数据】?','提示',{
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        service.post(url,data).then(
            (response:any) => {
                const data = response.data;
                if(data.code == -1){
                    callback(HandleEnum.FAILED,response.data);
                    ElMessage.error("操作失败！");
                    return;
                }
                callback(HandleEnum.SUCCESS,response.data);
                ElMessage.info("操作成功！");
            }).catch((error:any) => {
                callback(HandleEnum.FAILED,error);
                ElMessage.error("请求失败！");
        });
    });
}

function handleObjectDefault(defaultValue:any,targetValue:any){
    let result = targetValue;
    for(const key in defaultValue){
        if(result.hasOwnProperty(key) && result[key] != undefined){
            if(isPrimitive(defaultValue[key]) || isArray(defaultValue[key])){
                continue;
            }
            handleObjectDefault(defaultValue[key],result[key]);
            continue;
        }
        result[key] = defaultValue[key];
    }
    return result;
}

const isPrimitive = (value:any) => {
    return (
        typeof value === 'string' ||
        typeof value === 'number' ||
        typeof value === 'boolean' ||
        typeof value === 'undefined' ||
        value === null
    );
}

const isArray =  (value:any) => {
    return value instanceof Array;
}

export {deleteRow,HandleEnum,handleObjectDefault,isPrimitive,isArray}